package org.ielse.frame;

import org.ielse.frame.model.AppSettings;
import org.ielse.frame.t.cache.DiskLruCacheUtil;
import org.ielse.frame.t.litepal.LitePalApplication;
import org.ielse.frame.t.litepal.crud.DataSupport;
import org.ielse.frame.t.volley.BitmapCache;
import org.ielse.frame.t.volley.ImageLoader;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

public class App extends LitePalApplication {

	private AppSettings appSettings;

	private static App instance;
	private RequestQueue requestQueue;
	private ImageLoader imageLoader;
	private BitmapCache bitmapCache;
	private DiskLruCacheUtil diskLruCacheUtil;
	private Gson gson;

	@Override public void onCreate() {
		super.onCreate();
		instance = this;
		requestQueue = Volley.newRequestQueue(instance);
		bitmapCache = new BitmapCache();
		imageLoader = new ImageLoader(requestQueue, bitmapCache);
		diskLruCacheUtil = DiskLruCacheUtil.open(instance);
		gson = new Gson();

		appSettings = DataSupport.findFirst(AppSettings.class);
		if (appSettings == null) {
			appSettings = new AppSettings();
			appSettings.save();
		}
		// CrashHandler.setDefaultUncaughtExceptionHandler(this);
	}

	public AppSettings getAppSettings() {
		if (appSettings == null) {
			appSettings = DataSupport.findFirst(AppSettings.class);
			if (appSettings == null) {
				appSettings = new AppSettings();
				appSettings.save();
			}
		}
		return appSettings;
	}

	public RequestQueue getRequestQueue() {
		if (requestQueue == null) requestQueue = Volley.newRequestQueue(instance);
		return requestQueue;
	}

	public ImageLoader getImageLoader() {
		if (imageLoader == null) imageLoader = new ImageLoader(getRequestQueue(), getBitmapCache());
		return imageLoader;
	}

	public BitmapCache getBitmapCache() {
		if (bitmapCache == null) bitmapCache = new BitmapCache();
		return bitmapCache;
	}

	public DiskLruCacheUtil getDiskLruCacheUtil() {
		if (diskLruCacheUtil == null) diskLruCacheUtil = DiskLruCacheUtil.open(instance);
		return diskLruCacheUtil;
	}

	public Gson getGson() {
		if (gson == null) gson = new Gson();
		return gson;
	}

	@Override public void onTerminate() {
		super.onTerminate();
	}

	@Override public void onLowMemory() {
		super.onLowMemory();
	}

	public static synchronized App i() {
		return instance;
	}
}
